package com.zhihaoliang.moshi.biz.adapter

import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.zhihaoliang.moshi.biz.models.BlackjackHand
import com.zhihaoliang.moshi.biz.models.Card
import com.zhihaoliang.moshi.biz.models.Suit
import com.zhihaoliang.moshi.util.log


/**
 * @author 支豪亮
 * @date 2023/1/28 09:37
 */
class CardAdapter {

    @ToJson
    fun toJson(card: Card) = card.rank + card.suit.toString()

    @FromJson
    fun fromJson(card: String): Card {
        if (card.length != 2) throw JsonDataException("Unknown card: $card")
        val rank = card[0]
        return when (card[1]) {
            'C' -> Card(rank, Suit.CLUBS)
            'D' -> Card(rank, Suit.DIAMONDS)
            'H' -> Card(rank, Suit.HEARTS)
            'S' -> Card(rank, Suit.SPADES)
            else -> throw JsonDataException("unknown suit: $card")
        }
    }
}

fun parserCustom(){
    val text = """
        {
          "hidden_card": "6S",
          "visible_cards":[
            "4C",
            "AH"
          ]
        }
    """.trimIndent()

    val moshi = Moshi.Builder().add(CardAdapter()).add(KotlinJsonAdapterFactory()).build()
    val jsonAdapter = moshi.adapter(BlackjackHand::class.java)

    val blackjackHand = jsonAdapter.fromJson(text)
    log(blackjackHand.toString())
}